import { defineStore } from 'pinia'
import { mockLogin, mockGetUserInfo, logout } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { asyncRoutes } from '@/router'

export const useUserStore = defineStore('user', {
  state: () => ({
    token: getToken(),
    userInfo: {},
    roles: [],
    permissions: [],
    routes: []
  }),

  getters: {
    isLoggedIn: (state) => !!state.token,
    hasRole: (state) => (role) => state.roles.includes(role),
    hasPermission: (state) => (permission) => state.permissions.includes(permission)
  },

  actions: {
    // 登录
    async login(loginForm) {
      try {
        const response = await mockLogin(loginForm)
        this.token = response.data.token
        setToken(response.data.token)
        return response.data
      } catch (error) {
        throw error
      }
    },

    // 获取用户信息
    async getUserInfo() {
      try {
        const response = await mockGetUserInfo(this.token)
        this.userInfo = response.data.data.userInfo
        this.roles = response.data.data.roles
        this.permissions = response.data.data.permissions
        return response.data.data
      } catch (error) {
        throw error
      }
    },

    // 生成路由
    async generateRoutes() {
      const accessedRoutes = this.filterAsyncRoutes(asyncRoutes, this.roles)
      this.routes = accessedRoutes
      return accessedRoutes
    },

    // 过滤路由
    filterAsyncRoutes(routes, roles) {
      const res = []
      routes.forEach(route => {
        const tmp = { ...route }
        if (this.hasPermissionToRoute(tmp, roles)) {
          if (tmp.children) {
            tmp.children = this.filterAsyncRoutes(tmp.children, roles)
            // 如果子路由被过滤完了，但父路由有alwaysShow，仍然显示父路由
            if (tmp.children.length === 0 && !tmp.meta?.alwaysShow) {
              return // 不添加没有子路由的父路由
            }
          }
          res.push(tmp)
        }
      })
      return res
    },

    // 检查路由权限
    hasPermissionToRoute(route, roles) {
      if (route.meta && route.meta.roles) {
        return roles.some(role => route.meta.roles.includes(role))
      } else {
        return true
      }
    },

    // 检查当前用户是否有访问指定路由的权限
    checkRoutePermission(route) {
      return this.hasPermissionToRoute(route, this.roles)
    },

    // 登出
    async logout() {
      try {
        await logout()
      } catch (error) {
        console.error('Logout error:', error)
      } finally {
        this.token = ''
        this.userInfo = {}
        this.roles = []
        this.permissions = []
        this.routes = []
        removeToken()
        // 重新加载页面以清除动态路由
        window.location.reload()
      }
    },

    // 重置状态
    resetState() {
      this.token = ''
      this.userInfo = {}
      this.roles = []
      this.permissions = []
      this.routes = []
    }
  }
})
